/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { CloseCircleOutlined } from '@ant-design/icons'
import { Button, notification } from 'antd'
import { extend } from 'umi-request'

notification.config({
  maxCount: 3,
})

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户登录已过期，请重新登录',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
}

/**
 * 异常处理程序
 */

const errorHandler = (error) => {
  const { response = {} } = error
  const errortext = codeMessage[response.status] || response.statusText
  const { status } = response
  const key = 'error'

  console.log('error', error)

  if (parseInt(status, 10) === 401) {
    notification.open({
      key,
      message: errortext,
      duration: null,
      icon: <CloseCircleOutlined style={{ color: '#ef5350' }} />,
    })
    setTimeout(() => {
      notification.close(key)
    }, 3000)
  } else {
    notification.open({
      message: `请求错误 ${status}`,
      description: errortext,
      duration: 3000,
      icon: <CloseCircleOutlined style={{ color: '#ef5350' }} />,
      btn: (
        <Button
          type="primary"
          size="small"
          onClick={() => {
            window.location.reload()
          }}
        >
          刷新页面
        </Button>
      ),
    })
  }
}

// 替换
const newUrl = (url) => {
  const regStr = '[/]{1}'
  const reg = new RegExp(regStr, 'g')
  return url.replace(reg, '')
}

/**
 * 配置request请求时的默认参数
 */

export const SUAN_PAN = window.location.pathname === '/' ? '' : `/${newUrl(window.location.pathname)}`

const umiRequest = extend({
  errorHandler,
  credentials: 'include', // 默认请求是否带上cookie
  prefix: SUAN_PAN,
})

umiRequest.interceptors.request.use((url, { headers }) => {
  headers['X-Project-Id'] = getProjectId() || sessionStorage.getItem('projectId')
})

const promiseFun = (method, url, params = {}, needCode = false, resolve, reject, json = true) => {
  const postObj = {}
  if (json) {
    postObj.data = params
  } else {
    postObj.data = params
    postObj.requestType = 'form'
  }

  umiRequest[method](url, postObj)
    .then((res = {}) => {
      const { status, data = {}, msg = '操作失败' } = res
      const isDetail = /custom-form-ques/.test(window.location.href)
      const hash = window.location.hash?.split('#')?.[1]

      if (Number(status) === 401) {
        // notification.error({
        //   description: msg || '服务端报错,请重新登陆',
        // })
        localStorage.removeItem('loginSta')
        // 跳转云巧登录界面 401 402 403
        const backURL = encodeURIComponent(`${window.location.origin + window.location.pathname}#/login?redirect=${hash}`)
        // window.location = `http://sf-main.yunqiao.ingress.dxsp.tech/sso/login?service=${backURL}`
        window.location = `http://sf-api-gateway-xltest.xuelang-test.ingress.dxsp.tech/sso/login?service=${backURL}`
        return null
      }
      if (needCode) {
        resolve(res)
      } else if (Number(status) === 200) {
        resolve(data)
      } else {
        notification.error({
          message: '服务端错误',
          description: msg,
        })
        reject(res)
      }
      return null
    })
    .catch((e) => {
      console.log(e)
    })
}

export const getProjectId = () => {
  const defaultWorkSpace = sessionStorage.getItem('defaultWorkSpace')
  sessionStorage.setItem(
    'projectId',
    defaultWorkSpace && JSON.parse(defaultWorkSpace) && JSON.parse(defaultWorkSpace).id,
  )
  return defaultWorkSpace && JSON.parse(defaultWorkSpace) && JSON.parse(defaultWorkSpace).id
}

export default class Https {
  static get(url, params = null, reqConf = {}) {
    const { needCode } = reqConf
    return new Promise((resolve, reject) => {
      if (!params) {
        promiseFun('get', url, params, needCode, resolve, reject)
        return
      }
      let handleUrl = ''
      for (const key in params) {
        if (handleUrl !== '') {
          handleUrl += '&'
        }
        if (params[key] instanceof Object) {
          handleUrl += `${key}=${encodeURIComponent(JSON.stringify(params[key]))}`
        } else {
          handleUrl += `${key}=${encodeURIComponent(params[key])}`
        }
      }
      promiseFun('get', `${url}?${handleUrl}`, params, needCode, resolve, reject)
    })
  }

  static post(url, params, reqConf = {}) {
    const { needCode, json } = reqConf
    return new Promise((resolve, reject) => {
      promiseFun('post', url, params, needCode, resolve, reject, json)
    })
  }
}
